﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace intelliSys.Management.Automation.Profiler
{
    class UpdateTask
    {
        public string OriginalVersion
        {
            get;
            set;
        }
        public string Credential
        {
            get;
            set;
        }
        public string UID
        {
            get;
            set;
        }
        public string FTPServer = "ftp://soft.nankai.edu.cn";
        public string Directory = "/upload/";
        public string VersionFileName = "version.txt";
        public string NewVersion
        {
            get;
            private set;
        }
        public UpdateTask(string origVersion, string credential, string uID)
        {
            OriginalVersion = origVersion;
            Credential = credential;
            UID = uID;
        }
        public void Download(string uri, string filename)
        {
            FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
            reqFTP.Credentials = new NetworkCredential(UID, Credential);
            reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
            var response = reqFTP.GetResponse();
            var ftpStream = response.GetResponseStream();
            Stream outputStream = File.Create(filename);
            long cl = response.ContentLength;
            int bufferSize = 2048;
            int readCount;
            byte[] buffer = new byte[bufferSize];
            readCount = ftpStream.Read(buffer, 0, bufferSize);
            while (readCount > 0)
            {
                outputStream.Write(buffer, 0, readCount);
                readCount = ftpStream.Read(buffer, 0, bufferSize);
            }
            ftpStream.Close();
            outputStream.Close();
            response.Close();
        }
        public void DownloadNewVersion()
        {
        }
        public bool NewVersionDetected()
        {
            Download(FTPServer + Directory + VersionFileName, "version.txt");
            StreamReader sr = new StreamReader(File.Open("version.txt", FileMode.Open));
            var ver = sr.ReadToEnd();
            sr.Close();
            if (ver.CompareTo(OriginalVersion) > 0)
            {
                NewVersion = ver;
                return true;
            }
            else
            {
                return false;
            }
        }
    }
    class SecurityVerificationTask
    {
        public void Run()
        {
        }
    }
}
